/*
 * @Author: Mr.Mao
 * @Date: 2021-05-16 14:59:57
 * @LastEditTime: 2021-06-24 00:16:35
 * @Description: 
 * @LastEditors: Mr.Mao
 * @autograph: 任何一个傻子都能写出让电脑能懂的代码，而只有好的程序员可以写出让人能看懂的代码
 */
import mongoose, { Document, SchemaTypeOptions } from 'mongoose'
import { ExtractPropTypes } from "vue"
import { DocumentTransform } from './types'
import autoIncrement from 'mongoose-auto-increment'

// 基本地址
const DATABASE_PATH = "mongodb://localhost/construct-chatroom"

// 连接服务
mongoose.connect(DATABASE_PATH, {
  useNewUrlParser: true,
  useUnifiedTopology: true
})

// 监听连接
mongoose.connection.once('open', () =>
  console.log(`数据库连接成功, 地址: ${DATABASE_PATH}`)
)
mongoose.connection.once('close', () => console.log('数据库连接失败!'))

// 初始化自增 ID 扩展
autoIncrement.initialize(mongoose.connection)

/**
 * 创建模型 schema -> model
 * @param definition schema 映射
 * @param options schema 配置
 * @returns Model 模型
 */
export const createModel = <T = {[key:string]: SchemaTypeOptions<any>}>(
  definition: T,
  options?: mongoose.SchemaOptions
) => {
  const schema = new mongoose.Schema(definition, { ...options, versionKey: false })
  return (name: string) => {
    schema.plugin(autoIncrement.plugin, { model: name, field: '_id' })
    return mongoose.model<DocumentTransform<T>>(name, schema)
  }
}
export { mongoose }